class PostsController < ApplicationController
  #**
  # @apiDefine ReturnPost
  #
  # @apiSuccess {String} title 标题
  # @apiSuccess {String} content 内容
  # @apiSuccess {User} user 所属者
  #*

  #**
  # @apiDefine ReturnPostArray
  #
  # @apiSuccess {Post[]} _ 博文列表
  # @apiSuccess {String} _.title 标题
  # @apiSuccess {String} _.content 内容
  # @apiSuccess {User} _.user 所属者
  #*

  #**
  # @apiDefine PostParams
  #
  # @apiParam {Id} user_id 用户id
  # @apiParam {String} title 标题
  # @apiParam {String} content 内容
  #*

  #**
  # @api {get} /posts 列出所有博文
  # @apiName GetPosts
  # @apiGroup Post
  #
  # @apiUse ReturnPostArray
  #*
  #**
  # @api {get} /users/:user_id/posts 列出用户博文
  # @apiName GetPosts
  # @apiGroup Post
  #
  # @apiUse ReturnPostArray
  #*
  def index
    posts = prepare_query(Post.all)
    respond posts
  end

  #**
  # @api {post} /users/:user_id/posts 创建用户博文
  # @apiName PostPost
  # @apiGroup Post
  #
  # @apiUse PostParams
  # @apiUse ReturnPost
  #*
  def create
    post = Post.create!(post_param)
    render json: post
  end

  #**
  # @api {get} /posts/:id 查看博文
  # @apiName GetPost
  # @apiGroup Post
  #
  # @apiUse ReturnPost
  #*
  def show
    post = Post.find(params[:id])
    render json: post
  end

  #**
  # @api {put} /posts/:id 更改博文
  # @apiName PutPost
  # @apiGroup Post
  #
  # @apiUse PostParams
  # @apiUse ReturnPost
  #*
  def update
    post = Post.find(params[:id])
    post.update!(post_param)
  end

  #**
  # @api {delete} /posts/:id 删除博文
  # @apiName DeletePost
  # @apiGroup Post
  #*
  def destroy
    post = Post.find(params[:id])
    post.destroy
    head :no_content
  end

  private

  def post_param
    params.permit(:user_id, :title, :content)
  end
end
